<template>
  <div v-loading="loading" class="detail">
    <common-card v-if="type === 'other'" :info="commonInfo" />
    <el-tabs v-else v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基础信息" name="info">
        <basic-card
          v-if="type === 'environment' && activeName === 'info'"
          :is-admin="isAdmin"
          :status="taskInfo ? taskInfo.status : -1"
          :corp-info="corpInfo"
          @start="handleStart"
          @terminate="handleTerminate"
          @confirm="handleUpdate"
          @submit="handleSubmit"
          @correct="handleCorrect"
          @export="handleExport"
          @cancel="getTaskInfo"
        />

        <sec-basic-card
          v-if="type === 'security' && activeName === 'info'"
          :is-admin="isAdmin"
          :status="taskInfo ? taskInfo.status : -1"
          :basic-info="secBasicInfo"
          @start="handleStart"
          @terminate="handleTerminate"
          @confirm="handleUpdate"
          @submit="handleSubmit"
          @correct="handleCorrect"
          @cancel="getTaskInfo"
        />
      </el-tab-pane>
      <el-tab-pane label="巡查报告" name="report">
        <report-card
          v-if="type === 'environment' && activeName === 'report'"
          :is-admin="isAdmin"
          :status="taskInfo ? taskInfo.status : -1"
          :report-info="reportInfo"
          @start="handleStart"
          @terminate="handleTerminate"
          @confirm="handleUpdate"
          @submit="handleSubmit"
          @correct="handleCorrect"
          @export="handleExport"
          @cancel="getTaskInfo"
        />

        <sec-report-card
          v-if="type === 'security' && activeName === 'report'"
          :is-admin="isAdmin"
          :status="taskInfo ? taskInfo.status : -1"
          :basic-info="secBasicInfo"
          :report-info="secReportInfo"
          @start="handleStart"
          @terminate="handleTerminate"
          @confirm="handleUpdate"
          @submit="handleSubmit"
          @correct="handleCorrect"
          @export="handleExport"
          @cancel="getTaskInfo"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import axios from 'axios'
import { saveAs } from 'file-saver'
import store from '@/store'
import CommonCard from './CommonCard'
import BasicCard from './BasicCard'
import ReportCard from './ReportCard'
import SecBasicCard from './SecBasicCard'
import SecReportCard from './SecReportCard'
import { formatDatetime } from '@/utils'
import { getCookie, getToken } from '@/utils/auth'
import { getNewTask, updateNewTask, correctNewTask, updateTask, exportCorpInfo, exportReportInfo, exportTaskAllInfo, exportPromiseInfo, exportCheckInfo } from '@/api/task/task'

export default {
  name: 'TaskDetail',
  components: { CommonCard, BasicCard, ReportCard, SecBasicCard, SecReportCard },
  data() {
    return {
      // dicts: ['evn_pollution_apply_status', 'env_unloading_type', 'env_content_status', 'env_sys_basic_exist', 'env_finish_status', 'env_waste_water_target', 'env_drainage_system', 'env_waste_water_property', 'env_system_has_or_not', 'env_equipment_type', 'env_gas_pollution_status', 'env_gas_gas_pollution_status', 'env_eia_type', 'env_system_yes_no', 'env_contract_sign_status', 'env_task_product_process', 'env_task_publish', 'env_system_operation_status', 'env_task_rain_sewage_problem', 'env_task_gas_site_conditions', 'env_task_accord'],
      taskId: this.$route.params.taskId,
      type: this.$route.params.type,
      isAdmin: false, // 是否为该任务管理员
      loading: true,
      activeName: 'info',
      corpInfo: {},
      taskInfo: {},
      taskDetail: {},
      reportInfo: {},

      secBasicInfo: {},
      secTaskDetail: {},
      secReportInfo: {},
      commonInfo: {}
    }
  },
  created() {
    this.getTaskInfo()
  },
  methods: {
    async getTaskInfo() {
      const { data } = await getNewTask(this.taskId)
      this.loading = false
      this.isAdmin = ['admin', data.taskInfo.handlerName].includes(store.getters.name)
      this.corpInfo = data.corpInfo
      this.taskInfo = data.taskInfo
      this.taskDetail = data.taskDetail
      this.secBasicInfo = data.secBasicInfo
      this.secTaskDetail = data.secTaskDetail

      if (this.type === 'environment') {
        this.reportInfo = {
          taskInfo: {
            handlerName: this.taskInfo.handlerName || getCookie('username'),
            position: this.taskInfo.position,
            startTime: this.taskInfo.startTime || formatDatetime(new Date(), 'YYYY-MM-DDTHH:mm:ss'),
            num: this.taskInfo.num,
            conclusion: this.taskInfo.conclusion
          },
          ...data.taskDetail,
          hwStoreStatusInfos: data.taskDetail.hwStoreStatusInfos.map(item => {
            item.result = item.result || '符合'
            return item
          }),
          ownerMonitorStatus: {
            ownerMonitorStatus: data.taskDetail.ownerMonitorStatus
          },
          planPublishStatus: {
            planPublishStatus: data.taskDetail.planPublishStatus
          }
        }
      } else if (this.type === 'security') {
        this.secReportInfo = data.secTaskDetail
      } else if (this.type === 'other') {
        this.commonInfo = data.commonTask
      }
    },
    handleClick(tab) {
      this.activeName = tab.name
    },

    isArray(val) {
      return Object.prototype.toString.apply(val).slice(8, -1).toLowerCase() === 'array'
    },
    isObject(val) {
      return Object.prototype.toString.apply(val).slice(8, -1).toLowerCase() === 'object'
    },
    omitEmptyItem(arr) {
      const res = []
      arr.forEach(item => {
        const keys = Object.keys(item)
        let flag = false
        keys.forEach(v => {
          if (item[v] || item[v] === 0) flag = true
        })
        flag && res.push(item)
      })
      return res
    },
    getFormData(key, formData) {
      let corpInfo = { ...this.corpInfo }
      let taskInfo = { ...this.taskInfo }
      const taskDetail = { ...this.taskDetail }
      let secBasicInfo = { ...this.secBasicInfo }
      let secTaskDetail = [...this.secTaskDetail]
      let files = []
      let secFiles = []
      if (key === 'info') {
        corpInfo = {
          ...formData,
          busiType: formData.busiType.join(','),
          equipItems: this.omitEmptyItem(formData.equipItems),
          gasEquipmentItems: this.omitEmptyItem(formData.gasEquipmentItems),
          hwItems: this.omitEmptyItem(formData.hwItems),
          reportItems: this.omitEmptyItem(formData.reportItems),
          solidWasteItems: this.omitEmptyItem(formData.solidWasteItems)
        }
        if (corpInfo.mergencyStatus === '有') {
          taskDetail.mergencyInfo.mergencyPlanStatus = '有'
          taskDetail.mergencyInfo.mergencyPlanChange = taskDetail.mergencyInfo.mergencyPlanChange === '/' ? '' : taskDetail.mergencyInfo.mergencyPlanChange
          if (corpInfo.mergencyLagoonStatus !== '是') {
            taskDetail.mergencyInfo.mergencyLagoonStatus = '/'
          } else {
            taskDetail.mergencyInfo.mergencyLagoonStatus = taskDetail.mergencyInfo.mergencyLagoonStatus === '/' ? '' : taskDetail.mergencyInfo.mergencyLagoonStatus
          }
        } else {
          taskDetail.mergencyInfo.mergencyPlanStatus = '无'
          taskDetail.mergencyInfo.mergencyPlanChange = '/'
          taskDetail.mergencyInfo.mergencyLagoonStatus = '/'
        }
      } else if (key === 'report') {
        taskInfo = {
          ...taskInfo,
          ...formData.taskInfo
        }
        for (const param in taskDetail) {
          if (['ownerMonitorStatus', 'planPublishStatus'].includes(param)) {
            taskDetail[param] = formData[param][param]
          } else {
            taskDetail[param] = formData[param]
          }

          if (this.isObject(taskDetail[param]) && taskDetail[param].files) {
            files = [
              ...files,
              ...(taskDetail[param].files || []).filter(file => !file.id).map(file => {
                file.connectId = taskDetail[param].id
                return file
              })
            ]
          }
          if (this.isArray(taskDetail[param])) {
            taskDetail[param].forEach(item => {
              if (item.files) {
                files = [
                  ...files,
                  ...(item.files || []).filter(file => !file.id).map(file => {
                    file.connectId = item.id
                    return file
                  })
                ]
              }
            })
          }
        }
      } else if (key === 'sec-info') {
        secBasicInfo = formData
      } else if (key === 'sec-report') {
        secTaskDetail = formData
        formData.forEach(item => {
          if (item.fileList && item.fileList.length > 0) {
            secFiles = [
              ...secFiles,
              ...(item.fileList || []).filter(file => !file.id).map(file => {
                file.connectId = item.id
                return file
              })
            ]
          }
        })
      }
      return {
        files, secFiles, corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail
      }
    },
    async sendRequest(type, files, secFiles, corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail) {
      const data = {
        id: this.taskId,
        corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail
      }
      const promise = type === 'correct' ? correctNewTask(data) : updateNewTask(data)
      await promise
      if (files.length > 0 || secFiles.length > 0) {
        files.length > 0 && this.uploadFiles(files, '0')
        secFiles.length > 0 && this.uploadFiles(secFiles, '1')
      } else {
        this.getTaskInfo()
        this.$message({
          message: { update: '保存成功', correct: '更正成功', submit: '提交成功' }[type],
          type: 'success'
        })
      }
    },
    uploadFiles(files, busiType = '0') {
      let uploadedNum = 0
      files.forEach(async file => {
        const formData = new FormData()
        formData.append('file', file.raw)
        formData.append('connectId', file.connectId)
        formData.append('busiType', busiType)
        try {
          await axios({
            url: '/api/v1/security/basicFile/fileUpload',
            method: 'post',
            data: formData,
            headers: {
              'Content-type': 'multipart/form-data',
              'Authorization': 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
            }
          })
          uploadedNum += 1
          if (uploadedNum === files.length) {
            this.getTaskInfo()
            this.$message({
              message: '保存成功',
              type: 'success'
            })
          }
        } catch (e) {
          uploadedNum += 1
          this.$message({
            message: `文件 ${file.name} 上传失败`,
            type: 'none'
          })
          if (uploadedNum === files.length) {
            this.getTaskInfo()
            this.$message({
              message: '保存成功',
              type: 'success'
            })
          }
        }
      })
    },

    handleCorrect({ type, formData }) {
      const { files, secFiles, corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail } = this.getFormData(type, formData)
      this.sendRequest('correct', files, secFiles, corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail)
    },
    // 暂存
    handleUpdate({ type, formData }) {
      const { files, secFiles, corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail } = this.getFormData(type, formData)
      this.sendRequest('update', files, secFiles, corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail)
    },
    // 提交
    handleSubmit({ type, formData }) {
      this.$confirm(`确认完成任务 ?`, '完成', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { files, secFiles, corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail } = this.getFormData(type, formData)
        taskInfo.status = 2
        this.sendRequest('submit', files, secFiles, corpInfo, taskInfo, taskDetail, secBasicInfo, secTaskDetail)
      })
    },

    async updateStatus(status) {
      const taskInfo = { ...this.taskInfo }
      taskInfo.status = status
      const params = { status: status }

      await updateTask(taskInfo, params)
      this.taskInfo = taskInfo

      this.$message({
        message: '提交成功',
        type: 'success'
      })
    },
    handleStart() {
      this.$confirm(`确认启动任务 ?`, '启动', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateStatus(1)
      })
    },
    handleTerminate() {
      this.$confirm(`确认终止任务 ?`, '终止', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateStatus(3)
      })
    },
    async handleExport(type) {
      let res
      if (type === 'info') {
        res = await exportCorpInfo(this.taskId)
      } else if (type === 'report') {
        res = await exportReportInfo(this.taskId)
      } else if (type === 'all') {
        res = await exportTaskAllInfo(this.taskId)
      } else if (type === 'promise') {
        res = await exportPromiseInfo(this.taskId)
      } else if (type === 'check') {
        res = await exportCheckInfo(this.taskId)
      }

      saveAs(res.data.path, res.data.fileName)
    }
  }
}
</script>
<style lang="scss" scoped>
@import '../../../assets/styles/variables.scss';

.detail {
  padding: 20px;
  height: calc(100vh - 84px);
  ::v-deep .el-tabs {
    height: 100%;
    .el-tabs__content {
      height: calc(100% - 55px);
      .el-tab-pane {
        height: 100%
      }
    }
  }
  ::v-deep .input {
    width: 400px;
  }
  ::v-deep .pars-table {
    width: 800px;
    margin-bottom: 20px;
  }
  ::v-deep .line-one .el-form-item__label {
    line-height: 1.2;
  }
  ::v-deep .footer {
    flex-shrink: 0;
    width: 100%;
    padding: 10px 15px;
    background-color: #fff;
    display: flex;
    justify-content: center;
    border-top: 1px solid $border-color;
    z-index: 2;
    .btn {
      padding: 5px 20px;
      border: 1px solid $border-color;
      border-radius: 3px;
      font-size: 14px;
      margin: 0 20px;
      cursor: pointer;
    }
    .confirm {
      color: #fff;
      background-color: $primary-color;
    }
    .submit {
      color: #fff;
      background-color: $success-color;
    }
    .terminate {
      color: #fff;
      background-color: $danger-color;
    }
  }
}
</style>
